package com.sky.service.impl;

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.Setmeal_dishMapper;
import com.sky.result.PageResult;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private Setmeal_dishMapper setmeal_dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;

    @Transactional
    public void add(SetmealDTO dto) {
        List<SetmealDish> meal_dishs = dto.getSetmealDishes();//这个套餐与各个菜品的关系
        final LocalDateTime now = LocalDateTime.now();
        Setmeal meal = new Setmeal(dto.getId(), dto.getCategoryId(), dto.getName(), dto.getPrice(),dto.getStatus(), dto.getDescription(), dto.getImage(),now,now , BaseContext.getCurrentId(),BaseContext.getCurrentId());
        setmealMapper.add(meal);
        Long mealId = setmealMapper.getBytime(dto.getImage());
        if( dto.getId() == null){
            for(int k = 0; k < meal_dishs.size(); k++){
                SetmealDish smd = meal_dishs.get(k);
                smd.setSetmealId(mealId);
                setmeal_dishMapper.add(smd);
            }
        }//若套餐id没有传进来，则利用数据库自己自增的id，遍历每个list对象，增加到套餐菜品表
    }
    @Transactional
    public PageResult getBypage(SetmealPageQueryDTO dto){
        //PageHelper.startPage(dto.getPage(),dto.getPageSize());
        dto.setPage((dto.getPage()-1)*dto.getPageSize());
        List<SetmealVO> result = setmealMapper.getbypage(dto);
        for(int k = 0;k<result.size();k++){
            String categoryname = setmealMapper.getnamebycategoryid(result.get(k));
            result.get(k).setCategoryName(categoryname);
        }
        Long counts = setmealMapper.getcounts();
        return new PageResult(counts,result);
    }
    @Transactional
    //注意：要起售的套餐中，如包含未起售的菜品，则不能起售。
    public void start_or_stop(String status,String id){
        Long id_ = Long.parseLong(id);
        Integer status_ = Integer.parseInt(status);
        log.info("传进来status:{}",status_);
        if(status_ == 0)setmealMapper.startorstop(status_,id_);//停售则不用考虑
        else{
            List<Long> dish_ids = setmeal_dishMapper.getdishidByid(id_);//拿到该套餐的所有菜品id
            for(int k = 0;k < dish_ids.size();k++){
                if(dishMapper.getStatusByid(dish_ids.get(k)) == 0)
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
            setmealMapper.startorstop(status_,id_);//没问题则可以正常更新套餐状态
        }




    }
    @Transactional
    public  SetmealVO getmealByid(String id){
        Long id_ = Long.parseLong(id);
        Setmeal setmeal = setmealMapper.getmealByid(id_);
        String categoryName = categoryMapper.getCategoryName_by_Categoryid(setmeal.getCategoryId());
        List<SetmealDish> setmealDishList = setmeal_dishMapper.getlistBysetmeal_id(setmeal.getId());
        SetmealVO VO =new SetmealVO();
        BeanUtils.copyProperties(setmeal,VO);
        VO.setCategoryName(categoryName);
        VO.setSetmealDishes(setmealDishList);
        log.info("最终的VO：{}",VO);
        return VO;
    }
    @Transactional
    public void update(SetmealDTO dto){
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto,setmeal);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        List<SetmealDish> sdlist = dto.getSetmealDishes();
        log.info("setmeal：{}",setmeal);
        //修改setmeal表
        setmealMapper.update(setmeal);
        //修改setmeal_dish:逻辑是先删除原有的口味，再添加新的口味
        setmeal_dishMapper.delete(setmeal.getId());//根据套餐id把原本的口味删掉
        for(int k = 0;k < sdlist.size();k++){
            if(sdlist.get(k).getSetmealId() == null)sdlist.get(k).setSetmealId(dto.getId());//判断一下有没有setmealid
            setmeal_dishMapper.add(sdlist.get(k));//加入新口味
        }
    }

    @Transactional
    //注意，删除之前要检查套餐的状态，起售则不能删
    public void delete_setmeals(String ids){
        String [] IDS = ids.split(",");
        Integer len = IDS.length;
        for(int k = 0;k < len;k++){
            Long id = Long.parseLong(IDS[k]);
            if(setmealMapper.getSatusByid(id) == 1){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        //批量删除setmeal表中的套餐
        setmealMapper.deleteByid(IDS);
        //批量删除每个套餐的所有菜品
        setmeal_dishMapper.deletes(IDS);

    }
    @Transactional
    public List<Setmeal> getBycategoryId(Integer categoryid){
        return setmealMapper.getBycategoryId(categoryid);
    }
    public List<DishItemVO> getvos(Long id){
        return setmealMapper.getvos(id);
    }
}
